package com.itheima.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.OrderSettingService;
import com.itheima.contant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/orderSetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;

    /*将 日期与可预约人数 传入后台，并将数据插入到数据库*/
    @RequestMapping("/editOrderSetting")
    public Result editOrderSetting(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.editOrderSetting(orderSetting);
            return Result.success(MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            return Result.error(MessageConstant.ORDERSETTING_FAIL);
        }

    }

    /*批量导入预约数据*/
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) {
        try {
            List<String[]> list = POIUtils.readExcel(multipartFile);

            /*如果此表不为空*/
            if (list != null && list.size() > 0) {
                List<OrderSetting> OrderSettingList = new ArrayList<>();
                for (String[] strings : list) {
                    /*此行不为空*/
                    if (strings != null && strings.length > 0) {

                        DateTime data = DateUtil.parse(strings[0], "yyyy.MM.dd");
                        OrderSetting orderSetting =
                                new OrderSetting(data, Integer.parseInt(strings[1]));

                        OrderSettingList.add(orderSetting);
                    }
                }
                /*将表中的数据添加进数据库*/
                orderSettingService.upload(OrderSettingList);
            }

            return Result.success(MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            return Result.error(MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /*查询预约信息表*/
    @RequestMapping("/queryOrderSetting")
    public Result queryOrderSetting(@RequestParam("date") String date) {
        try {
            List<OrderSetting> orderSettingList = orderSettingService.queryOrderSetting(date);
            return Result.error("",orderSettingList);
        } catch (Exception e) {
            return Result.error("");
        }
    }
}
